<template>
  <div class="product-display-wrapper">
    <!-- 左边 -->
    <div class="display-part display-left">
      <ul class="input-wrapper">
        <li class="input-box">
          <div class="input-label">开始时间</div>
          <el-date-picker
            class="input-content"
            type="datetime"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间"
            v-model="productParams.startTime"
            @change="changeTime"
          >
          </el-date-picker>
        </li>
        <li class="input-box">
          <div class="input-label">结束时间</div>
          <el-date-picker
            class="input-content"
            type="datetime"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间"
            v-model="productParams.endTime"
            @change="changeTime"
          >
          </el-date-picker>
        </li>
        <li class="input-box">
          <div class="input-label">类型</div>
          <el-select
            class="input-content"
            size="small"
            v-model="productParams.type"
            @change="changeType"
          >
            <el-option
              v-for="(tp, idx) in types"
              :key="tp.value"
              :label="tp.type"
              :value="tp.value"
            >
            </el-option>
          </el-select>
        </li>
      </ul>
      <ul class="product-list">
        <li class="product-item" v-for="(pd, idx) in productList" :key="idx">
          <el-tooltip
            effect="light"
            placement="right"
            :content="pd.productName"
          >
            <div
              class="product-name"
              :class="{ 'is-active': activeProduct === idx }"
              @click="changeProduct(idx)"
            >
              {{ pd.productName }}
            </div>
          </el-tooltip>
        </li>
        <li class="product-item" v-if="!productList.length">
          <div class="product-empty no-user-select">暂无产品</div>
        </li>
      </ul>
    </div>
    <!-- pdf -->
    <div
      class="display-part display-middle"
      :style="{ 'padding-top': src && pageCount ? '0' : '40px' }"
    >
      <div class="pdf-btns" style="text-align: center" v-if="src && pageCount">
        <el-button
          class="ptf-btn"
          size="mini"
          :disabled="currentPage === 1"
          @click="changePdfPage(0)"
        >
          上一页
        </el-button>
        {{ currentPage }} / {{ pageCount }}
        <el-button
          class="ptf-btn"
          size="mini"
          :disabled="currentPage === pageCount"
          @click="changePdfPage(1)"
        >
          下一页
        </el-button>
      </div>
      <div
        class="display-pdf"
        :style="{ height: src && pageCount ? 'calc(100% - 40px)' : '100%' }"
      >
        <pdf
          :src="src"
          :page="currentPage"
          @num-pages="pageCount = $event"
          @page-loaded="currentPage = $event"
          @loaded="loadPdfHandler"
          v-if="src"
        >
        </pdf>
        <div
          v-else
          class="no-user-select"
          style="margin-top: 40%; text-align: center; color: #999"
        >
          暂无产品
        </div>
      </div>
    </div>
    <!-- 右边 -->
    <div class="display-part display-right">
      <ul class="input-wrapper">
        <li class="input-box">
          <div class="input-label">期数</div>
          <el-input v-model="pdf.productNo"></el-input>
        </li>
        <li class="input-box" v-if="pdf.content">
          <div class="input-label">内容</div>
          <el-input
            :autosize="{ minRows: 1, maxRows: 15 }"
            type="textarea"
            v-model="pdf.content"
          ></el-input>
        </li>
        <li class="input-box">
          <div class="input-label">签发</div>
          <el-input v-model="pdf.department"></el-input>
        </li>
      </ul>
      <div class="product-operate">
        <el-button
          class="product-btn"
          size="small"
          type="warning"
          @click="deleteProduct"
        >
          删除
        </el-button>
        <el-button
          class="product-btn"
          size="small"
          type="primary"
          @click="downloadProduct"
        >
          下载
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getAction, postAction, deleteAction, downFile } from '@/api/action';
import pdf from 'vue-pdf'
import { productType } from '@/utils/constant'
export default {
  name: 'ProductDisplay',
  components: { pdf },
  data() {
    return {
      urls: {
        pList: '/api/product/list', // 查所有产品数据
        delete: '/api/product/delete/', // 根据id删除产品数据
        idProduct: '/api/product/getId/', // 根据id查询产品数据
        pdf: '/api/product/downLocal/', // 预览\下载 产品
      },
      pageLoading: null,
      types: productType,
      productList: [],
      activeProduct: 0,
      productParams: {
        startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        type: 2,
        pageNo: 1,
        pageSize: 10,
      },
      pdf: {},
      src: '', // src需要展示的PDF地址
      currentPage: 1, // 当前展示的PDF页码
      pageCount: 0, // PDF文件总页码
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.getProductList();
    },
    // 获取产品列表数据
    getProductList() {
      postAction(this.urls.pList, this.productParams).then((res) => {
        console.log(res);
        if (res.object) {
          this.productList = res.object.records;
          this.changeProduct(0);
        } else {
          this.productList = [];
          this.pdf = {};
          this.src = "";
        }
      })
    },
    // 改变时间
    changeTime() { this.getProductList(); },
    // 切换类型
    changeType() { this.getProductList(); },
    // 切换产品
    changeProduct(index) {
      this.activeProduct = index;
      getAction(this.urls.idProduct + this.productList[index].id).then(res => {
        if (res.msg === '成功') {
          Object.assign(this.pdf, res.object);
          console.log(111, this.pdf);
          this.getPDF();
        }
      })
    },
    // 删除
    deleteProduct() {
      this.$confirm('是否缺认删除该文件?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 添加询问
        deleteAction(this.urls.delete + this.productList[this.activeProduct].id).then(res => {
          if (res.msg === '成功') {
            this.getProductList();
            this.$message({
              message: `【${this.productList[this.activeProduct].productName}】删除成功`,
              type: 'success',
            })
          }
        })
      }).catch(() => { /* this.$message({ type: 'info', message: '已取消删除' }); */ });
    },
    // 下载产品
    downloadProduct() {
      if (!this.productList.length) {
        this.$message.warning('没有产品');
        return false;
      }
      // 0-下载   1-在线预览
      const filename = this.productList[this.activeProduct].productName + '.docx';
      let url = `${this.urls.pdf}0/${filename}`;
      downFile(url).then(res => {
        console.log('下载', res);
        if (res.status === 200) {
          const { data } = res;
          if (!data) {
            this.$message.warning('文件下载失败');
            return;
          }

          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/text' }), filename);
          } else {
            const url = window.URL.createObjectURL(new Blob([data], { type: 'application/text' }));
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(url); // 释放掉blob对象
          }
        }
      })
    },
    // 预览产品
    async getPDF() {
      this.pageLoading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      // 0-下载   1-在线预览
      let url = `${this.urls.pdf}1/${this.productList[this.activeProduct].productName}.pdf`;
      url = decodeURI(encodeURI(url));
      this.currentPage = 0;
      this.src = await pdf.createLoadingTask(url);
      //   console.log('src', typeof this.src);
      this.src.promise.then(pdf => {
        this.pageLoading.close();
      }).catch(err => {
        this.$message({ message: '文件获取失败', type: 'error' })
        this.pageLoading.close();
      });
    },
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
      }
    },
    loadPdfHandler() {
      this.currentPage = 1
    },
  },
}
</script>

<style lang="scss">
.product-display-wrapper {
  display: flex;
  justify-content: space-between;
  position: absolute;
  left: 50%;
  top: 100px;
  width: 80%;
  height: calc(100% - 120px);
  transform: translateX(-50%);
  .display-part {
    height: 100%;
    border-radius: 4px;
    background-color: rgb(255, 255, 255);
    box-shadow: 2px 0px 9.5px 0.5px rgba(165, 165, 165, 0.3);

    .input-wrapper {
      .input-box {
        display: flex;
        align-items: flex-start;
        padding: 1em 0;
        .input-label {
          margin-right: 1em;
          width: 4em;
          line-height: 36px;
          text-align-last: justify;
          &::after {
            position: absolute;
            content: "：";
          }
        }
        .input-content {
          flex: 1px;
        }
      }
    }
    .product-operate {
      display: flex;
      justify-content: space-between;
      margin-top: 50px;
      .product-btn {
        flex: 1;
      }
    }
  }
  .display-left {
    padding: 30px;
    margin-right: 10px;
    width: 20%;
    min-width: 320px;
    display: flex;
    flex-direction: column;
    .product-list {
      margin-top: 1em;
      height: 50%;
      flex: 1;
      border: 1px solid rgb(192, 190, 190);
      border-radius: 4px;
      overflow-x: auto;
      .product-item {
        cursor: pointer;
        .product-name {
          font-family: "SourceHanSansCN";
          padding: 0.6em 1em;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: keep-all;
          white-space: nowrap;
          // &:not(:last-of-type) {
          border-bottom: 1px solid rgb(192, 190, 190);
          // }
          &.is-active {
            color: rgb(53, 144, 250);
          }
        }
        .product-empty {
          padding: 0.6em 1em;
          color: #999;
          text-align: center;
        }
      }
    }
  }
  .display-middle {
    padding-bottom: 20px;
    flex: 1;
    .pdf-btns {
      padding: 6px;
      text-align: center;
    }
    .display-pdf {
      margin: 0 auto;
      width: 90%;
      height: 100%;
      border-width: 1px;
      border-color: rgb(192, 190, 190);
      border-style: solid;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }
  .display-right {
    padding: 30px;
    margin-left: 10px;
    width: 20%;
    min-width: 330px;
    .input-wrapper {
      .input-box {
        .input-label {
          width: 3em;
        }
      }
    }
  }
}
</style>